import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from "ngx-bootstrap";
import {adSystemApiUrl, tuikeSystemUrl, AliyunOssOutputUrl} from "../../../config/api";
import {HttpService} from "../../lib/service/http.service";
import {Headers, RequestOptions} from "@angular/http";
import {PromoteService} from "../../member/promote/promote.service";
import {LoginService} from "../../lib/service/tuike-login.service";

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  // host: {
  //   '(document:click)': 'handleClick($event)',
  // },
  styleUrls: ['./task.component.scss'],
  providers: [PromoteService]
})
export class TaskComponent implements OnInit {

  aliyunOssOutputUrl = AliyunOssOutputUrl;
  searchData = '';
  status = '3';
  type: string;
  message: string;
  isShow = true;
  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 20;
  _isSpinning = false;
  counts = {};
  tempory_sales: number;

  editItem;

  pageSize = 20;

  taskList = [];

  reject_result = '';
  integral = null;
  other_intergral = '';
  activeIntergral;

  dailyList = [];
  dailyTotal = 0;
  editSrc = '';
  editId;
  taskTotal = 0;

  categories1 = [];
  secondCategory = {};
  first_category_list = [];
  second_category_list = [];

  categories = [];
  selectedCategory = '';
  firstCategory = null;
  fileList = [];
  picList = [];
  _value: any[] = null;
  editFirstCategory;
  editSecondCategory;
  description = '';
  edit = false;
  _options = [];
  info = [];
  cascaderStatus = false;
  first_category;
  second_category;
  flag = true;
  showWhere = '0';
  searchType = null;
  canVisit = false;

  tabs=[{
    name:"普通活动",
    value:0
  },{
    name:"秒杀活动",
    value:5
  }
  ];
  activity_type = 0;

  @ViewChild('editModal') public editModal: ModalDirective;

  constructor(
    private httpService: HttpService,
    private el: ElementRef,
    private promoteService: PromoteService,
    private loginService: LoginService
  ) {
  }

  ngOnInit() {
    this.getTaskList(1);
    this.canVisit = this.loginService.canVisitCheck('edit_taskmanage');
  }

  //重置
  reset() {
    this.searchData = '';
    this.searchType = '';
    this.searchType = null;
    this.showWhere = '0';
    this.getTaskList(1);
  }

  //搜索
  search() {
    this.getTaskList(1);
  }

  changeType(value) {
    let item=this.tabs[value.index];
    this.activity_type = item.value;
    this.currentPage = 1;
    this.getTaskList(1);
  }


  addEditSubmit() {
    this.submitTemporySales();
  }

  _console(e) {
    console.log(e);
  }

  keyDown(e) {
    e.code === 'Enter' ? this.search() : '';
  }

  loadData(e: { option: any, index: number, resolve: Function, reject: Function }): void {
    if (e.index === -1) {
      e.resolve(this.categories1);
      return;
    }
    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      option.loading = false;
      e.resolve(this.secondCategory[option.label]);
    }
  }

  selected(e) {
    if (e.length == 1) {
      this.cascaderStatus = e[0];
      // this.cascaderStatus = e[1];
      // this.first_category = this.editFirstCategory;
      // this.second_category = this.editSecondCategory;
    } else {
      this.first_category = e[0];
      this.second_category = e[1];
      this.cascaderStatus = e[2];
    }
  }

  cancel() {
    this.first_category = this.editFirstCategory;
    this.second_category = this.editSecondCategory;
    this.editModal.hide();
  }

  handler(e,e1) {
    this.cascaderStatus = true;
    setTimeout(() => {
      this.cascaderStatus = false;
      this.first_category = this.editFirstCategory;
      this.second_category = this.editSecondCategory;
    }, 0);
  }

  submitTemporySales() {
    // let first_category, second_category = '';
    // if (typeof(this._value[0]) == 'object') {
    //   first_category = this._value[0]['value'];
    //   second_category = this._value[1]['value'];
    // } else {
    //   first_category = this._value[0];
    //   second_category = this._value[1];
    // }

    // if (!/^\+?[1-9]\d*$/.test(this.tempory_sales + '')) {
    if (!/^\d+$/.test(this.tempory_sales + '')) {
      this.type = 'error';
      this.message = '销量为正整数';
      this.isShow = true;
      return;
    }
    const url = `${tuikeSystemUrl}/api/v1/admin/Task/edit_task`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const data = {
      id: this.editId,
      tempory_sales: this.tempory_sales,
      first_category: this.first_category,
      second_category: this.second_category,
      description: this.description
    };
    this.httpService.httpPostAuth(url, data, options).subscribe(res => {
      if (res.code === 200) {
        this.type = 'success';
        this.message = '修改成功';
        this.isShow = true;
        this.editModal.hide();
        this.tempory_sales = null;
        setTimeout(() => {
          this.getTaskList(this.currentPage);
        }, 100);
      }
    })
  }


  showEditModal(item) {
    this.editModal.show();
    this.editId = item.id;
    this.tempory_sales = item.tempory_sales;
    this.editFirstCategory = item.first_category;
    this.editSecondCategory = item.second_category;
    this.description = item.description;
    this._options = [];
    this._value = [];
    if (item.category_name) {
      let split = item.category_name.indexOf('/');
      let arr = [];
      arr.push(item.category_name.substring(0, split), item.category_name.substring(split + 1));
      this.info = [
        {
          label: arr[0],
          value: item.first_category
        },
        {
          label: arr[1],
          value: item.second_category
        }
      ];
      this._value = [
        {
          label: arr[0],
          value: item.first_category
        },
        {
          label: arr[1],
          value: item.second_category
        }
      ];
    } else {
      this._value = [];
      this.info = [];
    }
  }

  selectChange(e) {
    console.log(e);
  }

  closeMask() {
    this.el.nativeElement.querySelector('.mask').style.display = 'none';
  }

  closeCascader() {
    this.cascaderStatus ? this.cascaderStatus = false : '';
  }

  getTaskList(page) {
    this._isSpinning = true;
    let url = `${tuikeSystemUrl}/api/v1/admin/Task/task_list?page=${page}&pageSize=${this.pageSize}&activity_type=${this.activity_type}`;
    if (this.searchData) {
      url = url + '&task_name=' + this.searchData;
    }
    if (this.searchType) {
      url = url + '&first_category=' + this.searchType[0] + '&second_category=' + this.searchType[1];
    }
    if (this.showWhere) {
      url = url + '&status=' + this.showWhere;
    }
    // const url = `http://tuike.usexcx.com/api/v1/admin/Task/task_list?page=${page}&pageSize=${this.pageSize}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.taskList = res.data.list.data;
        this.first_category_list = res.data.first_category_list;
        this.second_category_list = res.data.second_category_list;
        this.categories1 = [];
        this.first_category_list.map((e, i) => {
          this.categories1.push({
            value: e.id,
            label: e.category_name,
          });
          this.secondCategory[e.category_name] = [];
          this.second_category_list.map((e1, i1) => {
            if (e1.parent_id === e.id) {
              this.secondCategory[e.category_name].push({
                value: e1.id,
                label: e1.category_name,
                isLeaf: true
              });
            }
          });
        });


        this.taskList.map((e, i) => {
          let fc = '';
          let sc = '';
          this.first_category_list.map((e1, i1) => {
            if (e1.id == e.first_category) {
              fc = e1.category_name;
            }
          });
          this.second_category_list.map((e2, i2) => {
            if (e2.id == e.second_category) {
              sc = e2.category_name;
            }
          });
          e['category_name'] = fc + '/' + sc;
        });
        this._isSpinning = false;
        this.taskTotal = res.data.list.total;
      }
    });
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.getTaskList(event.page);
  }
}
